package com.king.tv;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;

import com.google.gson.Gson;
import com.king.base.util.ToastUtils;
import com.king.tv.bean.AddUserBean;
import com.king.tv.dao.greendao.bean.User;
//import com.king.tv.dao.greendao.Utils.DbUserUtils;
import com.king.tv.dao.greendao.dao.DaoMaster;
import com.king.tv.dao.greendao.dao.DaoSession;
import com.king.tv.dao.greendao.dao.UserDao;
import com.king.tv.dao.greendao.manager.DaoManager;
import com.king.tv.dao.greendao.manager.ManagerFactory;
import com.king.tv.http.BaseCallModel;
import com.king.tv.http.HttpLoader;
import com.king.tv.mvp.base.PureActivity;
import com.king.tv.mvp.fragment.BBSFragment;
import com.king.tv.mvp.fragment.FollowFragment;
import com.king.tv.mvp.fragment.HomeFragment;
import com.king.tv.mvp.fragment.LiveFragment;
import com.king.tv.mvp.fragment.MineFragment;
import com.king.tv.util.SPUtils;
import com.zhangqie.zqvideolibrary.ZQVideoPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainActivity extends PureActivity {

    @BindView(com.king.tv.R.id.rbHome)
    RadioButton rbHome;
    @BindView(com.king.tv.R.id.rbLive)
    RadioButton rbLive;
    @BindView(com.king.tv.R.id.rbFollw)
    RadioButton rbFollw;
    @BindView(com.king.tv.R.id.rbMe)
    RadioButton rbMe;

    private HomeFragment homeFragment;

    private LiveFragment liveFragment;

    private FollowFragment followFragment;

    private MineFragment mineFragment;

    private BBSFragment bbsFragment;

    private boolean isExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getUser();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ZQVideoPlayer.releaseAllVideos();
    }

    private void getUser() {
    try{
        List<User> list = ManagerFactory.getInstance().getStudentManager().queryAll();
        if(list.size()>0){
            Log.i("tag","==========list"+list.get(0).toString());
            User user = list.get(0);
            updateUser(user);
        }else{
            getUserid();
        }
        // 创建数据
//        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MainActivity.this, "king.db", null);
//        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
//        DaoSession daoSession = daoMaster.newSession();
//        UserDao stuDao = daoSession.getUserDao();
//        stuDao.save(user);



//        HttpLoader httpLoader = new HttpLoader();
//        httpLoader.getHotM().subscribe(new Observer<String>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(String value) {
//                Log.i("tag","=========Result"+value.toString());
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
    } catch (Exception e) {
        Log.i("tag","============videoe"+e);
        e.printStackTrace();
    }
    }

    /**
     * 更新user信息
     * @param user
     */
    private void updateUser(User user) {
        HttpLoader.getInstance().getUser(user.getUsercode()).subscribe(new Observer<BaseCallModel<Object>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }
            @Override
            public void onNext(BaseCallModel<Object> value) {
                Gson gson = new Gson();
                String json = gson.toJson(value.getData());
                User user =gson.fromJson(json,User.class);
                ManagerFactory.getInstance().getStudentManager().deleteAll();
                ManagerFactory.getInstance().getStudentManager().save(user);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 获取userid
     */
    private void getUserid() {
        HttpLoader httpLoader = new HttpLoader();
        httpLoader.addUser().subscribe(new Observer<AddUserBean>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.i("tag","=========Result"+d.toString());
            }

            @Override
            public void onNext(AddUserBean value) {
                Log.i("tag","=========Result"+value.getData().getId().toString());
                Gson gson = new Gson();
                String json = gson.toJson(value.getData());
                User user =gson.fromJson(json,User.class);
                ManagerFactory.getInstance().getStudentManager().save(user);
                Log.i("tag","=========Result"+json);
                SPUtils.putString(MainActivity.this,"userid",value.getData().getId());
            }

            @Override
            public void onError(Throwable e) {
                Log.i("tag","=========Result"+e.toString());
            }

            @Override
            public void onComplete() {
                Log.i("tag","=========Result end");
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        isExit = false;
    }

    @Override
    public int getRootViewId() {
        return com.king.tv.R.layout.activity_main;
    }

    @Override
    public void initUI() {
        showLiveFragment();
    }


    @Override
    public void onBackPressed() {

        if(!isExit){
            ToastUtils.showToast(context,R.string.press_again_to_exit);
            isExit = true;
            EventBus.getDefault().post(isExit);
        }else{
            super.onBackPressed();
        }

    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onEventExit(Boolean isBool){
        SystemClock.sleep(1000);
        isExit = false;
    }


    public void showHomeFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(fragmentTransaction);
        if(homeFragment == null){
            homeFragment = HomeFragment.newInstance();
            fragmentTransaction.add(com.king.tv.R.id.fragmentContent,homeFragment);
        }
        commitShowFragment(fragmentTransaction,homeFragment);
    }

    public void showLiveFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(fragmentTransaction);
        if(liveFragment == null){
            liveFragment = LiveFragment.newInstance(getString(R.string.tab_home),null,true);
            fragmentTransaction.add(com.king.tv.R.id.fragmentContent,liveFragment);
        }

        commitShowFragment(fragmentTransaction,liveFragment);

    }

    public void showFollowFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        hideAllFragment(fragmentTransaction);
        if(followFragment == null){
            followFragment = FollowFragment.newInstance();
            fragmentTransaction.add(com.king.tv.R.id.fragmentContent,followFragment);
        }

        commitShowFragment(fragmentTransaction,followFragment);

    }

    public void showMineFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        hideAllFragment(fragmentTransaction);
        if(mineFragment == null){
            mineFragment = MineFragment.newInstance();
            fragmentTransaction.add(com.king.tv.R.id.fragmentContent,mineFragment);
        }

        commitShowFragment(fragmentTransaction,mineFragment);

    }

    public void showBBSFragment(){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        hideAllFragment(fragmentTransaction);
        if(bbsFragment == null){
            bbsFragment = BBSFragment.newInstance();
            fragmentTransaction.add(com.king.tv.R.id.fragmentContent,bbsFragment);
        }
        commitShowFragment(fragmentTransaction,bbsFragment);

    }

    public void commitShowFragment(FragmentTransaction fragmentTransaction,Fragment fragment){
        fragmentTransaction.show(fragment);
        fragmentTransaction.commit();
    }

    public void hideAllFragment(FragmentTransaction fragmentTransaction){
        hideFragment(fragmentTransaction,homeFragment);
        hideFragment(fragmentTransaction,liveFragment);
        hideFragment(fragmentTransaction,followFragment);
        hideFragment(fragmentTransaction,mineFragment);
        hideFragment(fragmentTransaction,bbsFragment);
    }

    private void hideFragment(FragmentTransaction fragmentTransaction,Fragment fragment){
        if(fragment!=null){
            fragmentTransaction.hide(fragment);
        }
    }

    public void replaceFragment(@IdRes int id, Fragment fragment) {

        getSupportFragmentManager().beginTransaction().replace(id, fragment).commit();
    }

    @OnClick({com.king.tv.R.id.rbHome, com.king.tv.R.id.rbLive, com.king.tv.R.id.rbFollw, com.king.tv.R.id.rbMe, R.id.rbShequ})
    public void onClick(View view) {
        switch (view.getId()) {
            case com.king.tv.R.id.rbHome:
                showLiveFragment();
                break;
            case com.king.tv.R.id.rbLive:

                showHomeFragment();
                break;
            case com.king.tv.R.id.rbFollw:
                showFollowFragment();
                break;
            case com.king.tv.R.id.rbMe:
                showMineFragment();
                break;
            case R.id.rbShequ:
                showBBSFragment();
                break;
        }
    }
}
